import 'dart:async';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/service/resource_service.dart';
import 'package:ball_lion/utils/sp_utils.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/entity/other/resource_entity.dart';

class AdsFloatWidget extends StatefulWidget {
  const AdsFloatWidget({super.key});

  static final ResourceService resource = Get.find<ResourceService>();
  static ResourceEntity? currentAds;
  static String? currentRoute;
  static void Function()? update;

  static void checkAds(String? route) {
    currentRoute = route;
    var ads = resource.floatAds.filter((item) => item.button == route);
    if (ads.hasValue &&
        (DateTime.tryParse(SpUtils.floatAds?[route] ?? "") ??
                DateTime.now().subtract(const Duration(seconds: 5)))
            .isBefore(DateTime.now())) {
      currentAds = ads.first;
    } else {
      currentAds = null;
    }
    update?.call();
  }

  @override
  State<AdsFloatWidget> createState() => _AdsFloatWidgetState();
}

class _AdsFloatWidgetState extends State<AdsFloatWidget> {
  ResourceEntity? get currentAds => AdsFloatWidget.currentAds;
  String? get currentRoute => AdsFloatWidget.currentRoute;
  final sc = StreamController.broadcast();

  @override
  void initState() {
    AdsFloatWidget.update = () {
      sc.add(null);
    };
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
        stream: sc.stream,
        builder: (context, snapshot) {
          return SizedBox(
            width: Get.width,
            height: Get.height,
            child: Stack(
              children: [
                Positioned(
                  bottom: 160,
                  right: 8,
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        if (currentAds != null)
                          Image.asset(
                                  width: 16,
                                  Utils.getImgPath("search_close.png"))
                              .tap(() {
                            if (currentRoute.hasValue) {
                              Map<String, String> map = {
                                currentRoute!: DateTime.now()
                                    .add(const Duration(days: 1))
                                    .toIso8601String()
                              };
                              SpUtils.setFloatAds(map);
                              AdsFloatWidget.checkAds(currentRoute!);
                            }
                          }),
                        if (currentAds != null)
                          GestureDetector(
                            onTap: () {
                              if (currentAds?.href != null) {
                                Utils.doJump(currentAds!.href!);
                              }
                            },
                            child: CachedNetworkImage(
                              width: 60,
                              height: 60,
                              fit: BoxFit.cover,
                              imageUrl: currentAds?.imgUrl ?? "",
                              errorWidget: (context, url, error) => Container(),
                            ),
                          ),
                      ]),
                ),
              ],
            ),
          );
        });
  }
}
